// src/websocket.js
let listSocket;
let detailSocket;

export function connectListWebSocket(userId, onMessageCallback) {
  const url = `wss://customer.tjbbb.com/chat/ws?user_id=${userId}&receiver_id=0`;
  listSocket = new WebSocket(url);

  listSocket.onopen = () => console.log("List WebSocket connected");

  listSocket.onmessage = (event) => {
    const message = JSON.parse(event.data);
    onMessageCallback(message);
  };

  listSocket.onclose = () => console.log("List WebSocket closed");

  listSocket.onerror = (error) => console.error("List WebSocket error:", error);
}

export function connectDetailWebSocket(userId, receiverId, onMessageCallback) {
  if (detailSocket) {
    detailSocket.close();
  }
  const url = `wss://customer.tjbbb.com/chat/ws?user_id=${userId}&receiver_id=${receiverId}`;
  detailSocket = new WebSocket(url);

  detailSocket.onopen = () => console.log("Detail WebSocket connected");

  detailSocket.onmessage = (event) => {
    const message = JSON.parse(event.data);
    onMessageCallback(message);
  };

  detailSocket.onclose = () => console.log("Detail WebSocket closed");

  detailSocket.onerror = (error) =>
    console.error("Detail WebSocket error:", error);
}

export function closeDetailWebSocket() {
  if (detailSocket) {
    detailSocket.close();
    detailSocket = null;
  }
}

export function sendDetailMessage(content) {
  if (detailSocket && detailSocket.readyState === WebSocket.OPEN) {
    detailSocket.send(content);
  } else {
    console.error("Detail WebSocket is not connected");
  }
}